package com.test.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/write1")
    public void write(){
        String token = String.valueOf(Math.random());
        //写入list并且把新value往左推
        stringRedisTemplate.opsForList().leftPush("test:app:",token);
        System.out.println(stringRedisTemplate.opsForList().size("test:app:"));

        //取出最左边的一个值，其实就是最后一个写入的值
        String ss = stringRedisTemplate.opsForList().leftPop("test:app:");
        System.out.println(ss);

        System.out.println(stringRedisTemplate.opsForList().size("test:app:"));

        //取出最右边的一个值，其实就是第一个写入的值
        stringRedisTemplate.opsForList().rightPop("test:app:");

        //取出该key所有值，-1表示最后一个
        List<String> list = stringRedisTemplate.opsForList().range("test:app:",0,-1);
        list.forEach( tmp -> {
            System.out.println(tmp);
        });
    }

    @GetMapping("/write")
    public void testRedis() {
        List<String> list = new ArrayList<>();
        list.add("吴大为");
        list.add("李大庆");
        list.add("吴大为");
        if (redisTemplate.opsForList().size("user:list") <= 0) {
            redisTemplate.opsForList().leftPush("user:list", JSON.toJSONString(list));
        }
        List<String> list1 = new ArrayList<>();
        list1.add("吴大为1");
        List<String> list2 = new ArrayList<>();
        list2.add("吴大为222");
        list2.add("吴大为333");
        list2.add("吴大为444");
        redisTemplate.opsForList().leftPushAll("user:list", list1, list2);
        redisTemplate.opsForValue().set("user:name", "李四");
    }

    @GetMapping("/read")
    public Object read() {
        return redisTemplate.opsForValue().get("user:name");
    }

    @GetMapping("/read1")
    public List read1() {
        List<Object> list = redisTemplate.opsForList().range("user:list", 0, -1);
//        List<String> list1 = JSON.parseArray((String) list.get(0), String.class);

        //取得key中某个index的值
        Object ooo = redisTemplate.opsForList().index("user:list", 0);
        Long lsize = redisTemplate.opsForList().size("user:list");
        list.forEach(ele -> {
            System.out.println(ele);
        });
        return list;
    }
}
